<?php


namespace App\Http\observer;


use App\Models\Chicken;
use App\Models\ChickenRank as RankModel;
use App\Models\EggLog;
use App\Models\Sys as SysModel;
use App\Models\User as UserModel;

class ChickenObserver
{
    public function updated(Chicken $chicken)
    {
        $rank=RankModel::where("experience","<=",$chicken["experience"])->orderBy("experience","asc")->first();
        if ($rank){
            Chicken::where("id",$chicken->id)->update(["rank"=>$rank["id"]]);
        }

        $big_chicken_feed=SysModel::getValue("big_chicken_feed");
        if($big_chicken_feed<=$chicken["experience"]){
            Chicken::where("id",$chicken->id)->update(["grade"=>1]);
        }

        if ($chicken->grade==1){
            $rank=RankModel::where("id",$chicken->rank)->first();
            if(!$rank)
            {
                return null;
            }
            if ($rank["egg_time"]<=$chicken["food"]){
                UserModel::where("id",$chicken->uid)->increment("egg",1);
                Chicken::where(["id"=>$chicken->id])->update(["food"=>0]);
                $log=[
                    "uid"=>$chicken->uid,
                    "type"=>0,
                    "num"=>1,
                    "state"=>0
                ];
                EggLog::create($log);
            }

        }

    }
}
